#include"server.hpp"

//设置为全局
static uint64_t conn_id = 0;
unordered_map<uint64_t,PtrConnection> _conns;//管理连接id和连接
EventLoop base_loop;
LoopThreadPool* loop_pool;
// int lst_fd = 0;
// vector<LoopThread> threads(2);
// int next_loop = 0;

void HandlerClose(Channel* channel)
{
    DBG_LOG("close:%d\n",channel->Fd());
    channel->Remove();//移除监控
    delete channel;//释放文件描述符
}

void HandlerAny(EventLoop* loop,uint64_t timerid)
{
    loop->RefreshTask(timerid);
    return;
}

void HandlerRead(Channel* channel)
{
    int fd = channel->Fd();
    char buff[1024] = {0};
    int ret = recv(fd,buff,1023,0);
    if(ret <= 0)
    {
        cout << "链接释放" << endl;
        return HandlerClose(channel);
    }//链接释放
    channel->EnableWrite();//启动可写事件
    DBG_LOG("client say: %s\n",buff);
}

void HandlerWrite(Channel* channel)
{
    int fd = channel->Fd();
    char* data = "hello Client..";
    int ret = ::send(fd,data,strlen(data),0);
    if(ret <= 0)
    {return HandlerClose(channel);}
    channel->DisableWrite();//关闭写监控
}

//服务器关闭链接回调
void ConnectionDestroy(const PtrConnection& conn)
{
      _conns.erase(conn->Id());
}


void OnConnected(const PtrConnection& conn)
{
     DBG_LOG("NEW Connection:%p",conn.get());
}

void OnClosed(const PtrConnection& conn)
{
     DBG_LOG("Close Connection:%p",conn.get());
}

void OnMessage(const PtrConnection& conn,Buffer* buf)
{
//    if(lst_fd != conn->Fd())
//      DBG_LOG("On Message..");
   DBG_LOG("%s",buf->ReadPos());
   buf->MoveReadIdx(buf->ReadAbleSize());
   string str = "Hello World";
   conn->Send(str.c_str(),str.size());
//    conn->ShutDown();//测试收到一次就关闭
}


//监听套接字触发可读事件时,获取新链接 为新链接设置回调,开启他们的可读事件
void NewConnection(int fd) 
{
    // int fd = lis_channel->Fd();
    // int newfd = accept(fd,NULL,NULL);
    // if(newfd < 0)
    // {
    //     cout << "accept error" << endl;
    //     return;
    // }
    conn_id++;
    DBG_LOG("新链接的fd:%d",fd);
    //分配线程池的线程给新链接,即分配eventLoop进行事件监控
    PtrConnection conn(new Conncetion(loop_pool->NextLoop(),conn_id,fd));
    cout << "gain a new link" << endl;
    conn->SetMessageCallBack(std::bind(OnMessage,std::placeholders::_1,std::placeholders::_2));
    conn->SetConnectedCallBack(std::bind(OnConnected,std::placeholders::_1));
    conn->SetSvrClosedCallBack(std::bind(ConnectionDestroy,std::placeholders::_1));
    conn->EnableInactiveRelease(12); //启动-非活跃链接销毁
    //先启动非活跃连接销毁再启动读监控
    conn->Established();//就绪初始化:设置回调 启动读监控
    _conns.insert(std::make_pair(conn_id,conn));//放进服务器组件管理
    DBG_LOG("-----------------------NEW---------------------------");
}

int main()
{ 
    // srand(time(0));
    printf("主线程：%p",(void*)pthread_self());
    ///*初始化线程池*/
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    //创建监听套接字
    Acceptor acceptor(&base_loop,8081);
    // DBG_LOG("主线程Loop的eventfd:%d",base_loop.EventFd());
    // lst_fd = acceptor.LstFd();
    // cout << "监听套接字fd:" << lst_fd << endl;
    acceptor.SetAcceptCallBack(std::bind(NewConnection,std::placeholders::_1));
    acceptor.Listen();
    
    while(1)
    {   //开始监控
        base_loop.Start();
    }
    return 0;
}












// int main()
// {
//     Socket serverSocket;
//     bool ret = serverSocket.CreateServer(8080);
//     if(ret)
//     {
//         ERR_LOG("create server error");
//     }
//     while(1)
//     {
//          int newfd = serverSocket.Accept();
//          if(newfd < 0) continue;
//          Socket cli_socket(newfd);
//          char buffer[1024] = {0};
//          int ret = cli_socket.Recv(buffer,1023);
//          if(ret < 0) 
//          {
//             ERR_LOG("ret < 0");
//             cli_socket.Close();
//             continue;
//          }
//          cli_socket.Send(buffer,ret);
//          cli_socket.Close();
//     }
//     serverSocket.Close();
//     return 0;
// }
